package com.yuhang.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 *
 */
@Component //此处注解一定要写，不然会被springboot忽略，此处注解相当于bean标签
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            HttpSession session = request.getSession();
            int state = 0;
            if(session.getAttribute("state")!=null){
                state = (int)session.getAttribute("state");
            }
            if(state!=0){
                return true;
            }else{
                response.sendRedirect(request.getContextPath()+"/login.jsp");
                return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
                //如果设置为true时，请求将会继续执行后面的操作
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
            //如果设置为true时，请求将会继续执行后面的操作
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}